﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace VMCCryptoLib.HashEncryption
{
    public class SHA256Hash
    {
    	#region --- Methods to hash a string and a file with SHA256 algorithm
        /// <summary>
        /// Method to hash a string with SHA256
        /// </summary>
        /// <param name="input">a string to hash</param>
        /// <returns>a hashed string</returns>
        public static string ThisString(string input)
        {
            string result = string.Empty;
            SHA256 sha = new SHA256Managed();
            byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(input));

            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte b in hash)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }
            return result = stringBuilder.ToString();
        }
        
        /// <summary>
        /// Method to hash file with SHA256 algorithm
        /// </summary>
        /// <param name="fileName">a path if file to hash</param>
        /// <returns>hashed string</returns>
        public static string ThisFile(string fileName)
        {
        	string rs = string.Empty;
        	
        	FileStream fileStream =  new FileStream(fileName,FileMode.Open,FileAccess.Read); // Open and read content of file
        	SHA256 sha256 = new SHA256Managed();
        	byte[] hash = sha256.ComputeHash(fileStream); // Hash file
        	fileStream.Close(); // Close stream
        	
        	StringBuilder strBuilder = new StringBuilder(); // Create a string builder to store a hashed string of this file
        	
        	foreach(byte b in hash) // Loop throught a array of hash
        	{
        		strBuilder.AppendFormat("{0:x2}",b);
        	}
        	
        	return rs = strBuilder.ToString(); // Return hashed string of this file
        }
        #endregion
    }
}
